package com.dyna.core.validator;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.util.HashSet;
import java.util.Set;
 
/**
 * 只能提交指定的值
 * 自定义校验
 */
@Documented
@Constraint(validatedBy = { ListValidator.ListValueConstraintValidator.class, ListValidator.ListStringValueConstraintValidator.class }) // 指定校验器，这里不指定时，就需要在初始化时指定
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ListValidator {
 
    // 默认的提示内容
    String message() default "请选择正确的值";
 
    Class<?>[] groups() default { };
 
    Class<? extends Payload>[] payload() default { };
 
    int[] values() default { }; //数值数组，提交的值只能是数组里面
 
    String[] strValues() default { }; //字符串数组，提交的值只能是数组里面
 
    class ListValueConstraintValidator implements ConstraintValidator<ListValidator, Integer> {
 
        private Set<Integer> set = new HashSet<>();
 
        /**
         * 初始化方法
         */
        @Override
        public void initialize(ListValidator constraintAnnotation) {
            int[] values = constraintAnnotation.values();
            for (int val : values) {
                set.add(val);
            }
        }
 
        /**
         * 判断是否校验成功
         */
        @Override
        public boolean isValid(Integer value, ConstraintValidatorContext context) {
            return set.contains(value);
        }
    }
 
    class ListStringValueConstraintValidator implements ConstraintValidator<ListValidator, String> {
 
        private Set<String> set = new HashSet<>();
 
        /**
         * 初始化方法
         */
        @Override
        public void initialize(ListValidator constraintAnnotation) {
            String[] values = constraintAnnotation.strValues();
            for (String val : values) {
                set.add(val);
            }
        }
 
        /**
         * 判断是否校验成功
         */
        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            return set.contains(value);
        }
    }
}